package com.example.fw;

import com.example.tests.FolderData;
import com.example.utils.ListOf;
import org.netbeans.jemmy.operators.*;

import java.awt.*;

public class FoldersHelper extends HelperBase{

	public FoldersHelper(AppManager manager) {
		super(manager);
	}
	
	public FoldersHelper createFolder(FolderData folderData) throws Exception {
        manager.getMenuHelper().pushCreateFolder();
        JDialogOperator dialog = new JDialogOperator(mainFrame);
        new JTextFieldOperator(dialog).setText(folderData.getName());
        new JButtonOperator(dialog, "OK").push();
        String warningMessage = waitMessageDialog("Warning", 3000);
        if (warningMessage != null) {
            throw new Exception("Method unexpected result: " + warningMessage);
        }
        cachedFolders = null;
		return this;
	}

	public FoldersHelper removeFolder(int index) {
        selectFolder(index);
        manager.getMenuHelper().pushRemoveFolder();
        JDialogOperator dialog = new JDialogOperator(mainFrame);
        new JButtonOperator(dialog, "Yes").push();
        cachedFolders = null;
		return this;
	}
	
	public ListOf<FolderData> getFolders() {
        if (cachedFolders == null) {
			rebuildCache();
		}
		return cachedFolders;
	}	
	
	// --------------------------------------------------------------------------------------------

	private ListOf<FolderData> cachedFolders;
	
	private void rebuildCache() {
		cachedFolders = new ListOf<FolderData>();

        JTreeOperator tree = new JTreeOperator(mainFrame);
        Object[] children = tree.getChildren(tree.getRoot());
        for (Object child : children) {
            String name = child.toString() ;
            cachedFolders.add(new FolderData().withName(name));
        }
    }

    private void selectFolder(int index) {
        JTreeOperator tree = new JTreeOperator(mainFrame);
        Point pointToClick = tree.getPointToClick(index);
        tree.clickMouse(pointToClick.x, pointToClick.y, 1);
    }
}
